package pers.xiaojun.boot.module.system.controller.auth;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import pers.xiaojun.boot.common.pojo.CommonResult;
import pers.xiaojun.boot.module.system.controller.auth.vo.AuthLoginReqVO;
import pers.xiaojun.boot.module.system.controller.auth.vo.AuthLoginRespVO;
import pers.xiaojun.boot.module.system.controller.auth.vo.AuthPermissionInfoRespVO;
import pers.xiaojun.boot.module.system.service.auth.AuthService;
import pers.xiaojun.boot.module.system.service.permission.PermissionService;
import pers.xiaojun.boot.security.config.properties.SecurityProperties;
import pers.xiaojun.boot.security.util.SecurityUtils;
import pers.xiaojun.boot.tenant.core.annotation.TenantIgnore;
import pers.xiaojun.boot.web.core.annotation.AdminApi;

/**
 * 认证相关接口
 *
 * @author xiaojun
 * @since 2025-10-04
 */
@Tag(name = "用户认证")
@RestController
@AdminApi
@RequestMapping("/system/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final PermissionService permissionService;
    private final SecurityProperties securityProperties;


    @PostMapping("/login")
    @PermitAll
    @Operation(summary = "登录")
    public CommonResult<AuthLoginRespVO> login(@RequestBody @Valid AuthLoginReqVO reqVO) {
        return CommonResult.success(authService.login(reqVO));
    }

    @PostMapping("/logout")
    @Operation(summary = "登出")
    public CommonResult<?> login(HttpServletRequest request) {
        authService.logout(SecurityUtils.extractTokenAuthorization(request, securityProperties.getTokenHeader(), securityProperties.getTokenPrefix()));
        return CommonResult.success(true);
    }

    @PostMapping("/refresh-token")
    @PermitAll
    @Operation(summary = "刷新Token")
    @Parameter(name = "refreshToken", description = "刷新令牌", required = true)
    public CommonResult<AuthLoginRespVO> refreshToken(@RequestParam("refreshToken") String refreshToken) {
        return CommonResult.success(authService.refreshAccessToken(refreshToken));
    }

    @GetMapping("/permission")
    @Operation(summary = "获取当前用户的权限信息")
    public CommonResult<AuthPermissionInfoRespVO> getUserPermission() {
        return CommonResult.success(permissionService.getUserPermission());
    }

}
